#!/bin/sh
# License: Creative Commons Public Domain Dedication (CC0 1.0)
#          <https://creativecommons.org/publicdomain/zero/1.0/>

[ -z "${MDEV}" ] && exit 22

DEV="$(echo ${MDEV} | sed 's/\(.*[a-z]\)\(.*\)/\1/')"
PART="$(echo ${MDEV} | sed 's/\(.*[a-z]\)\(.*\)/\2/')"

case $DEV in
vd*)
	TYPE=virtio
	;;
sd*)
	TYPE=ata
	;;
*)
	exit 33
	;;
esac

NAME=
if [ -f "/sys/class/block/${DEV}/device/vpd_pg83" ]
then
	# An existing vpd_pg83 node can still fail to read, #569990
	if cat "/sys/class/block/${DEV}/device/vpd_pg83" >/dev/null 2>&1
	then
		NAME=$(echo "$(cat "/sys/class/block/${DEV}/device/vpd_pg83")" | cut -c 36-95 | sed -e 's/ \+/_/g' -e "s/\(.*\)_/${TYPE}-\1${PART:+-part$PART}/")
	fi
fi

if [ -z "${NAME}" -a -x "/lib/udev/scsi_id" ]
then
	# Some systems like VMware don't expose Vital Product Data (VPD) via sysfs
	# but will expose at least some information when VM setting "disk.EnableUUID"
	# is set.
	if /lib/udev/scsi_id -p 0x83 -g -d "/dev/${DEV}" >/dev/null 2>&1
	then
		TYPE=scsi
		SERIAL=$(/lib/udev/scsi_id -p 0x83 -g -d "/dev/${DEV}" 2>/dev/null)
		SERIAL="${SERIAL// /}"
		if [ -n "${SERIAL}" ]
		then
			NAME="${TYPE}-${SERIAL}${PART:+-part$PART}"
		fi
	fi
fi

[ -z "${NAME}" ] && exit 44

mkdir -p /dev/disk/by-id
ln -sf "../../${MDEV}" "/dev/disk/by-id/${NAME}"
